// pages/court/court.js
const app = getApp();
var common = require("../../resources/config/config.js");
var utils = require("../../utils/util.js");


Page({
  /**
   * 页面的初始数据
   */
  
  data: {
    labels: ['日期', '运动', '总价：', '提交', '¥'],
    sports_lang: [],
    sports: [],
    language: '',
    date: '',
    index: 0,
    sportId:1,
    courts: [],
    times: ["08-09", "09-10", "10-11", "11-12", "12-13", "13-14", "14-15", "15-16", "16-17", "17-18"],
    bookingTable: [],
    row_id: null,
    column_id: null,
    total: 0,
    booked: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      language: options.language,
      date: options.date,
      index: options.index,
      sportId: options.sportId,
      sports_lang: app.globalData.sports_with_lang,
      sports: app.globalData.sports_with_lang.zh
    })
    var self = this;
    
    if (this.data.language == 'EN') {
      this.setData({
        labels: ['Date', 'Sport', 'Total: ', 'Submit', '¥'],
        sports: app.globalData.sports_with_lang.en
      })
    };

    loadBookingStatus(this.data.sportId, 
                      this.data.date, 
                      this.data.times,
                      function(court, bookingTable){
                        self.setData({
                            courts:court,
                            bookingTable: bookingTable
                          })
                      });
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },

  bindTap_row: function (e) {
    var new_row_id = parseInt(e.currentTarget.id);
    this.data.row_id = new_row_id;
    var current_total = this.data.total;
//get court id
    var courtId = this.data.courts[this.data.column_id].id;
    var parentId = this.data.courts[this.data.column_id].parent_id;
    var courtsToDisactivate = [];
    for (var i = 0; i < this.data.courts.length;i++){
      if (this.data.courts[i].parent_id==courtId){
        courtsToDisactivate.push(i);
      }
      if (this.data.courts[i].id == parentId){
        courtsToDisactivate.push(i);
      }
    }

//select the session
    if (this.data.bookingTable[this.data.row_id][this.data.column_id][1] == 1) {
      this.data.bookingTable[this.data.row_id][this.data.column_id][1] = 2;
      this.data.total = current_total + this.data.bookingTable[this.data.row_id][this.data.column_id][0];
      for (var i = 0; i < courtsToDisactivate.length;i++){
        //disable the sessions linked
        this.data.bookingTable[this.data.row_id][courtsToDisactivate[i]][1]=0;
      }
      this.setData({
        bookingTable: this.data.bookingTable,
        total: this.data.total,
      })
    }
//dis-select the session
    else if (this.data.bookingTable[this.data.row_id][this.data.column_id][1] == 2) {
      this.data.bookingTable[this.data.row_id][this.data.column_id][1] = 1;
      this.data.total = current_total - this.data.bookingTable[this.data.row_id][this.data.column_id][0];
      for (var i = 0; i < courtsToDisactivate.length; i++) {
        //re-enable the disabled sessions
        if(this.checkIfChildrenHasBeenSelected(this.data.courts[courtsToDisactivate[i]].id, this.data.column_id)){
          continue;
        }
        this.data.bookingTable[this.data.row_id][courtsToDisactivate[i]][1] = 1;
      }
      this.setData({
        bookingTable: this.data.bookingTable,
        total: this.data.total,
      })
    }
  },

  bindTap_cell: function (e) {
    var new_column_id = parseInt(e.currentTarget.id);
    this.data.column_id = new_column_id;
  },

  checkIfChildrenHasBeenSelected: function (courtId){
    var childrenId= [];
    for(var i = 0; i< this.data.courts.length; i++){
      if(this.data.courts[i].parent_id==courtId){
        childrenId.push(i);
      }  
    }
    var status=1;
    for(var index=0;index<childrenId.length;index++){
      //get the status of the corresponding cell
      status = this.data.bookingTable[this.data.row_id][childrenId[index]][1]
      if(status==0||status==2){
        return true;
      }
    }
    return false;
  },

  bindNavigate: function (e) {
    this.data.booked = [];

    for (var i = 0; i < this.data.bookingTable.length;i++) {
      for (var j = 0; j < this.data.bookingTable[0].length;j++) {
        if (this.data.bookingTable[i][j][1]==2) {
          var bookingObj={
            bookingTime: this.data.times[i],
            courtsName: this.data.courts[j].name,
            courtsId: this.data.courts[j].id
          };
          this.data.booked.push(bookingObj);
          console.log(this.data.booked);
        }
      }
    }
    if(this.data.booked.length==0){
      wx.showModal({
        title: '',
        content: app.globalData.messages.atLeastOneSession,
        showCancel: false,
        
        success: function (res) {
          if (res.confirm) {
            console.log('Ok')
            return;
          } 
        },
        fail: function (res) {
          console.log(res.errMsg)
        }
      })
      return;
    }
    else{
        var x = '';
        x = '../order/order' + '?language=' + this.data.language + 
                                '&date=' + this.data.date + 
                                '&sportId=' + this.data.sportId + 
                                '&index=' + this.data.index + 
                                '&booked=' + JSON.stringify(this.data.booked) + 
                                '&total=' + this.data.total;
        console.log(x);
        wx.navigateTo({
          url: x,
        })
    }
  },
})

function loadBookingStatus(sport, date, timelist, callback){
  //get court by sport and date
  console.log("sport :" + sport);
  console.log("date :" + date);
  var parameters = "?sportId=" + sport +"&includBookins=true&includMinutesForTime=false";
  console.log(common.getApiLink("getCourts") + parameters)
  utils.req_get(common.getApiLink("getCourts") + parameters, function (courts){
    var court = courts.cours;
    console.log(convertToBookingTable(court, timelist));
    callback(convertToCourts(court), convertToBookingTable(court, timelist));
  });
}
function convertToBookingTable(court,timelist){
  var courtNb = court.length;
  //init bookings
  var times = timelist;
  var timeNb = times.length;
  var bookingTable = [];
  for (var i = 0; i < courtNb; i++) {
    //column
    var price = court[i].price;
    var bookings = court[i].bookings;
    for (var j = 0; j < timeNb; j++) {
      //row
      var time = times[j];
      var booked = 1;
      if (bookingTable[j] == null) {
        bookingTable[j] = [];
      }
      for (var n = 0; n < bookings.length; n++) {
        if (time == bookings[n].time) {
          booked = 0;
        }
      }
      bookingTable[j][i] = [];
      bookingTable[j][i][0] = price;
      bookingTable[j][i][1] = booked;
    }
  }

  return bookingTable;
}
function convertToCourts(court){
  var courtNb = court.length;
  //init court
  var courtList = [];
  for (var i = 0; i < courtNb; i++) {
    courtList[i] = {name:court[i].name,
      id: court[i].coursId,
      parent_id: court[i].parentId}
  }
  console.log(courtList);

  return courtList;
}

